package br.com.upper.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.hibernate.Transaction;


public class TxProxy implements InvocationHandler {

	private Object obj;

    public static Object newInstance(Object obj) {

    	return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
                .getClass().getInterfaces(), new TxProxy(obj));
    }
    
    private TxProxy(Object obj) {
		this.obj = obj;
	}

	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		Transaction transaction = HibernateUtil.getTransaction();

		try {
			transaction.begin();
			Object result = method.invoke(this.obj, args); 
			if(!transaction.wasCommitted()){
				transaction.commit();
			}
			return result;

		} catch (InvocationTargetException e) {
			transaction.rollback();
			throw e;

		} catch (Exception e) {
			transaction.rollback();
			throw e;
		}
    }

}
